package my.georings.service;

import my.georings.data.MyLocation;
import android.content.Context;
import android.media.AudioManager;
import android.media.RingtoneManager;
import android.net.Uri;

public class SettingsChanger {

	
	public static MyLocation getDefaultRingSettings(Context context){
		MyLocation defaultOne = new MyLocation();
		
		AudioManager am = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
		
		if(am.getRingerMode() == AudioManager.RINGER_MODE_VIBRATE){
			defaultOne.setMute(true);
			defaultOne.setVibra(true);
			return defaultOne;
		}else if(am.getRingerMode() == AudioManager.RINGER_MODE_SILENT){
			defaultOne.setMute(true);
		}else{
			// check volume and ringtone
			Uri uri = RingtoneManager.getActualDefaultRingtoneUri(context.getApplicationContext(), RingtoneManager.TYPE_RINGTONE);
			if(uri != null){
				defaultOne.setChangeRing(true);
				defaultOne.setRing(uri);
			}
			
			defaultOne.setChangeVolume(true);
			defaultOne.setVolume(am.getStreamVolume(AudioManager.STREAM_RING)*10/am.getStreamMaxVolume(AudioManager.STREAM_RING));
		}
		return defaultOne;
	}
	
	
	
	public static boolean changeSettingsAccordingToLocation(MyLocation newLocation, Context context){
		
		if(!newLocation.isON())
			return false;
		
		AudioManager am = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
		
		// mute && vibra
		if(!newLocation.isMute()){
			am.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
			am.setVibrateSetting(	AudioManager.VIBRATE_TYPE_RINGER,
									newLocation.isVibra() ? AudioManager.VIBRATE_SETTING_ON: AudioManager.VIBRATE_SETTING_OFF);
		}
		else if(newLocation.isMute() && newLocation.isVibra()){
			am.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
			return true;
		}
		else if(newLocation.isMute() && !newLocation.isVibra()){
			am.setRingerMode(AudioManager.RINGER_MODE_SILENT);
			return true;
		}
		
		// ring
		if(newLocation.isChangeRing())
			RingtoneManager.setActualDefaultRingtoneUri(context, RingtoneManager.TYPE_RINGTONE, newLocation.getRing());
		
		// volume
		if(newLocation.isChangeVolume()){
			am.setStreamVolume(	AudioManager.STREAM_RING, 
								newLocation.getVolume() * am.getStreamMaxVolume(AudioManager.STREAM_RING)/10, 
								AudioManager.FLAG_ALLOW_RINGER_MODES);
		}
		
//		Log.d("::::::::::::TAK::::::::::::", "settings changed");
		
		return true;
	}
}
